package com.ebuy.servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ebuy.dao.ProductDAO;
import com.ebuy.dao.ProductTypeDAO;
import com.ebuy.model.Product;
import com.google.gson.Gson;

public class AddProductServlet extends BaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String productName = request.getParameter("productName");
		Integer type = Integer.parseInt("" + request.getParameter("type"));
		String description = request.getParameter("description");
		String price = request.getParameter("price");
		String stocks = request.getParameter("stocks");

		Product product = new Product();
		ProductTypeDAO dao = new ProductTypeDAO();

		product.setName(productName);
		product.setType(dao.getSingleProductType(type));
		product.setDescription(description);
		product.setPrice(Float.parseFloat(price));
		product.setStocks(Integer.parseInt(stocks));

		ProductDAO dao2 = new ProductDAO();
		product = dao2.createProduct(product);

		Map<String, Object> data = new HashMap<String, Object>();

		data.put("id", product.getId());
		data.put("productName", productName);
		data.put("type", product.getType().getName());
		data.put("description", description);
		data.put("price", price);
		data.put("stocks", stocks);

		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(new Gson().toJson(data));
	}

}
